package com.googlecode.wmlynar.javadoctc.analyzers.tests;

import java.util.Map;

import com.googlecode.wmlynar.javadoctc.domain.JavaDocClassPool;
import com.googlecode.wmlynar.javadoctc.domain.JavaDocMethod;
import com.thoughtworks.qdox.JavaDocBuilder;
import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;

public class UnitTestCollector {

	public JavaDocClassPool collect(JavaDocBuilder builder) {

		JavaDocClassPool pool = new JavaDocClassPool();

		JavaClass[] classes = builder.getClasses();
		for(JavaClass clas : classes) {
			if(!clas.isA("junit.framework.TestCase")) {
				continue;
			}
			//System.out.println(clas.getFullyQualifiedName());
			JavaMethod[] methods = clas.getMethods();
			for(JavaMethod method : methods) {
				DocletTag[] tags = method.getTags();
				if(tags.length == 0) {
					continue;
				}

				DocletTag myTag = method.getTagByName("javadoctest");
				Map map = myTag.getNamedParameterMap();

				String classStr = (String) map.get("class");
                String methodStr = (String) map.get("method");
                String textStr = (String) map.get("text");

//				DocletTag classTag = method.getTagByName("coverage.class");
//				DocletTag methodTag = method.getTagByName("coverage.method");
//				DocletTag sentenceTag = method.getTagByName("coverage.sentence");
//
//				if((classTag!=null || methodTag!=null || sentenceTag!=null) &&
//						(classTag==null || methodTag==null || sentenceTag==null)) {
//					throw new RuntimeException("coverage.class or coverage.method or coverage.sentence not present in test " + clas.getFullyQualifiedName() + "."+method.getName());
//				}
//
//				if(methodTag == null) {
//					continue;
//				}

				//System.out.println(QdoxUtils.getMethodSignature(method));

				//System.out.println(classTag.getValue());
				//System.out.println(methodTag.getValue());
				//System.out.println(sentenceTag.getValue().replaceAll("\\s"," "));

				JavaDocMethod met = new JavaDocMethod();
				met.setName(classStr);
				met.setJavadoc(textStr);

				pool.addMethodToClass(methodStr.replaceAll("\\s"," ").trim(), met);
			}
		}

		return pool;
	}
}
